// 管理员案件管理页面
const auth = require('../../../utils/auth')
const minLivingAllowanceAPI = require('../../../api/minLivingAllowance')

Page({
  data: {
    userInfo: {},
    // 全局加载状态
    globalLoading: false,
    globalLoadingText: '管理数据加载中...',
    // 案件列表数据
    casesList: [],
    // 筛选和搜索
    searchKeyword: '',
    statusFilter: 'all', // all, pending, completed, rejected
    categoryFilter: 'all', // all, civil-affairs, agriculture-rural, urban-rural-construction, infrastructure, environment, dispute
    dateFilter: 'all', // all, today, week, month
    // 分页
    currentPage: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    // 统计信息
    stats: {
      total: 0,
      pending: 0,
      approved: 0,
      rejected: 0
    },
    // 筛选选项
    statusOptions: [
      { value: 'all', label: '全部状态', color: '#64748b' },
      { value: 'pending', label: '待处理', color: '#dc2626' },
      { value: 'approved', label: '已通过', color: '#059669' },
      { value: 'rejected', label: '已驳回', color: '#dc2626' }
    ],
    categoryOptions: [
      { value: 'all', label: '全部', icon: '📂' },
      { value: 'civil-affairs', label: '民政服务', icon: '🏛️' },
      { value: 'agriculture-rural', label: '农业农村', icon: '🌾' },
      { value: 'urban-rural-construction', label: '城乡建设', icon: '🏗️' },
      { value: 'infrastructure', label: '基础设施', icon: '🛣️' },
      { value: 'environment', label: '环境保护', icon: '🌱' },
      { value: 'dispute', label: '纠纷调解', icon: '⚖️' }
    ],
    dateOptions: [
      { value: 'all', label: '全部时间', icon: '📅' },
      { value: 'today', label: '今天', icon: '🕐' },
      { value: 'week', label: '本周', icon: '📆' },
      { value: 'month', label: '本月', icon: '🗓️' }
    ],
    // 操作相关
    showFilter: false,
    selectedCases: [],
    showBatchActions: false
  },

  // 显示全局加载
  showGlobalLoading(text = '管理数据加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad() {
    this.loadUserInfo()
    this.loadCasesList()
    this.loadStats()
  },

  onShow() {
    // 每次显示页面时都重新加载数据，确保数据是最新的
    console.log('onShow 被调用，准备重新加载数据')
    // 添加防抖机制，避免频繁调用
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer)
    }
    this.refreshTimer = setTimeout(() => {
      this.loadCasesList(true)
      this.loadStats()
    }, 100)
  },

  onUnload() {
    // 页面卸载时清理定时器
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer)
      this.refreshTimer = null
    }
  },

  // 加载用户信息
  loadUserInfo() {
    const role = auth.getCurrentRole()
    if (!role || role !== 'admin') {
      wx.showToast({
        title: '权限不足',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
    
    const userInfo = wx.getStorageSync('USER_INFO') || {}
    this.setData({ userInfo })
  },

  // 加载案件列表
  loadCasesList(refresh = false) {
    console.log('loadCasesList 被调用，refresh:', refresh, '当前页码:', this.data.currentPage, '当前数据长度:', this.data.casesList.length)
    
    if (this.data.loading) {
      console.log('正在加载中，跳过本次请求')
      return
    }
    
    // 如果是刷新，立即清空现有数据并重置分页
    if (refresh) {
      console.log('执行刷新操作，清空现有数据')
      this.setData({
        currentPage: 1,
        casesList: [],
        hasMore: true,
        loading: true
      })
      
      // 使用 setTimeout 确保 setData 完成后再发起请求
      setTimeout(() => {
        this.performDataLoad(1)
      }, 50)
      return
    }
    
    // 非刷新情况，直接执行数据加载
    this.performDataLoad(this.data.currentPage)
  },

  // 执行实际的数据加载
  performDataLoad(page) {
    this.setData({ loading: true })

    const params = {
      page: page,
      limit: this.data.pageSize,
      keyword: this.data.searchKeyword,
      status: this.data.statusFilter !== 'all' ? this.data.statusFilter : '',
      startDate: this.data.dateFilter !== 'all' ? this.getDateRange(this.data.dateFilter).start : '',
      endDate: this.data.dateFilter !== 'all' ? this.getDateRange(this.data.dateFilter).end : ''
    }

    console.log('请求参数:', params)

    // 调用API获取数据
    minLivingAllowanceAPI.getAllApplications(params)
      .then(res => {
        console.log('API响应:', res)
        
        if (res.success) {
          const applications = res.data.applications || []
          const pagination = res.data.pagination || {}
          
          // 将申请数据转换为案件格式
          const formattedCases = this.formatApplicationsToCases(applications)
          
          // 确保数据处理的原子性
          let newCases
          if (page === 1) {
            // 第一页：完全替换现有数据
            newCases = this.deduplicateCases(formattedCases)
            console.log('第一页数据，完全替换现有数据')
          } else {
            // 后续页：追加到现有数据，并进行去重
            const combinedCases = [...this.data.casesList, ...formattedCases]
            newCases = this.deduplicateCases(combinedCases)
            console.log('后续页数据，追加到现有数据并去重')
          }
          
          console.log('数据处理结果:', {
            page,
            formattedCasesLength: formattedCases.length,
            existingCasesLength: this.data.casesList.length,
            newCasesLength: newCases.length
          })
          
          // 使用 setTimeout 确保数据更新的原子性
          setTimeout(() => {
            this.setData({
              casesList: newCases,
              loading: false,
              hasMore: pagination.hasNextPage || false,
              currentPage: page
            })
            
            // 更新统计数据
            this.updateStatsFromAPI(applications)
            
            if (page === 1) {
              wx.stopPullDownRefresh()
            }
          }, 10)
        } else {
          throw new Error(res.message || '获取数据失败')
        }
      })
      .catch(error => {
        console.error('获取案件列表失败:', error)
        
        this.setData({
          loading: false,
          casesList: page === 1 ? [] : this.data.casesList
        })
        
        if (page === 1) {
          wx.stopPullDownRefresh()
        }
        
        wx.showToast({
          title: error.message || '获取数据失败',
          icon: 'none',
          duration: 2000
        })
      })
  },

  // 生成案件数据
  generateMockCases() {
    const statuses = ['pending', 'approved', 'rejected']
    const users = [
      { name: '张三', phone: '13812345678', idCard: '320123199001011234' },
      { name: '李四', phone: '13987654321', idCard: '320123198502151234' },
      { name: '王五', phone: '13698765432', idCard: '320123197803201234' },
      { name: '赵六', phone: '13512345678', idCard: '320123199504151234' },
      { name: '钱七', phone: '13765432109', idCard: '320123198206101234' },
      { name: '孙八', phone: '13456789012', idCard: '320123199708251234' },
      { name: '周九', phone: '13321098765', idCard: '320123197912151234' },
      { name: '吴十', phone: '13210987654', idCard: '320123198411201234' }
    ]

    // 基于实际申请表单生成案件数据
    const applicationCases = this.generateApplicationCases(users, statuses)
    const complaintCases = this.generateComplaintCases(users, statuses)
    
    return [...applicationCases, ...complaintCases]
  },

  // 生成申请类案件数据
  generateApplicationCases(users, statuses) {
    const cases = []
    
    // 最低生活保障申请
    const minIncomeCases = [
      {
        title: '最低生活保障申请',
        description: '申请人因家庭收入低于当地最低生活保障标准，申请最低生活保障',
        type: 'application',
        category: 'civil-affairs',
        subCategory: 'min-income',
        formData: {
          name: '张三',
          idCard: '320123199001011234',
          phone: '13812345678',
          address: '江苏省南京市江宁区某某村123号',
          familySize: '3',
          monthlyIncome: '1200',
          incomeSource: '务农收入',
          reason: '家庭主要劳动力因病丧失劳动能力，收入微薄，生活困难'
        }
      },
      {
        title: '最低生活保障申请',
        description: '申请人因家庭收入低于当地最低生活保障标准，申请最低生活保障',
        type: 'application',
        category: 'civil-affairs',
        subCategory: 'min-income',
        formData: {
          name: '李四',
          idCard: '320123198502151234',
          phone: '13987654321',
          address: '江苏省南京市江宁区某某村456号',
          familySize: '4',
          monthlyIncome: '1500',
          incomeSource: '打工收入',
          reason: '夫妻双方均为临时工，收入不稳定，子女上学费用高'
        }
      }
    ]

    // 临时救助申请
    const reliefCases = [
      {
        title: '临时救助申请',
        description: '申请人因突发困难需要临时救助',
        type: 'application',
        category: 'civil-affairs',
        subCategory: 'relief',
        formData: {
          name: '王五',
          idCard: '320123197803201234',
          phone: '13698765432',
          address: '江苏省南京市江宁区某某村789号',
          difficultyType: '医疗支出困难',
          eventDate: '2024-01-15',
          expense: '15000',
          applyAmount: '5000',
          usage: '用于支付医疗费用，缓解家庭经济压力',
          bankName: '中国农业银行',
          bankAccount: '6228481234567890123'
        }
      }
    ]

    // 养老补贴申请
    const pensionCases = [
      {
        title: '养老补贴申请',
        description: '申请人申请养老补贴',
        type: 'application',
        category: 'civil-affairs',
        subCategory: 'pension-subsidy',
        formData: {
          name: '赵六',
          idCard: '320123199504151234',
          phone: '13512345678',
          address: '江苏省南京市江宁区某某村321号',
          age: '68',
          familySize: '2',
          monthlyIncome: '800',
          incomeSource: '退休金',
          subsidyType: '基础养老补贴',
          reason: '年龄较大，无其他收入来源，生活困难'
        }
      }
    ]

    // 宅基地申请
    const homesteadCases = [
      {
        title: '宅基地申请',
        description: '申请人申请宅基地用于建房',
        type: 'application',
        category: 'urban-rural-construction',
        subCategory: 'homestead-apply',
        formData: {
          name: '钱七',
          idCard: '320123198206101234',
          phone: '13765432109',
          address: '江苏省南京市江宁区某某村654号',
          hukouAddress: '江苏省南京市江宁区某某村654号',
          liveAddress: '江苏省南京市江宁区某某村654号',
          applyType: '新建',
          location: '第一组东侧地块',
          area: '120',
          usage: '住宅',
          reason: '原有房屋年久失修，需要新建住房'
        }
      }
    ]

    // 农机购置补贴申请
    const machineryCases = [
      {
        title: '农机购置补贴申请',
        description: '申请人申请农机购置补贴',
        type: 'application',
        category: 'agriculture-rural',
        subCategory: 'machinery-subsidy',
        formData: {
          name: '孙八',
          idCard: '320123199708251234',
          phone: '13456789012',
          address: '江苏省南京市江宁区某某村987号',
          machineType: '拖拉机',
          model: '久保田 KX-123',
          serialNo: 'KB2024001234',
          purchaseDate: '2024-01-20',
          dealer: '南京农机销售有限公司',
          invoiceAmount: '45000',
          subsidyCategory: '中央农机购置补贴',
          bankName: '中国工商银行',
          bankAccount: '6222021234567890123'
        }
      }
    ]

    // 合并所有申请案件
    const allApplicationCases = [...minIncomeCases, ...reliefCases, ...pensionCases, ...homesteadCases, ...machineryCases]
    
    allApplicationCases.forEach((caseData, index) => {
      const user = users[index % users.length]
      const status = statuses[Math.floor(Math.random() * statuses.length)]
      const createTime = new Date()
      createTime.setDate(createTime.getDate() - Math.floor(Math.random() * 30))
      
      cases.push({
        id: `case_${Date.now()}_${index}`,
        title: caseData.title,
        description: caseData.description,
        type: caseData.type,
        category: caseData.category,
        subCategory: caseData.subCategory,
        status: status,
        user: {
          id: `user_${index}`,
          name: user.name,
          phone: user.phone,
          avatar: ''
        },
        formData: caseData.formData,
        createTime: createTime.toISOString(),
        updateTime: new Date().toISOString(),
        assignee: status === 'pending' ? null : '管理员',
        deadline: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
        attachments: Math.floor(Math.random() * 4) + 1,
        comments: Math.floor(Math.random() * 3)
      })
    })
    
    return cases
  },

  // 生成投诉举报类案件数据
  generateComplaintCases(users, statuses) {
    const cases = []
    const complaintTemplates = [
      {
        title: '道路损坏投诉',
        description: '村内主干道路面破损严重，影响村民出行安全',
        type: 'complaint',
        category: 'infrastructure',
        formData: {
          complaintType: '基础设施',
          location: '村内主干道',
          description: '道路路面多处破损，坑洼不平，雨天积水严重',
          urgency: '高'
        }
      },
      {
        title: '噪音扰民举报',
        description: '附近工厂夜间生产噪音过大，影响村民休息',
        type: 'complaint',
        category: 'environment',
        formData: {
          complaintType: '环境污染',
          location: '村东侧工厂',
          description: '工厂夜间生产产生巨大噪音，严重影响村民正常休息',
          urgency: '中'
        }
      },
      {
        title: '邻里纠纷调解',
        description: '村民之间因土地边界问题产生纠纷',
        type: 'complaint',
        category: 'dispute',
        formData: {
          complaintType: '邻里纠纷',
          location: '村西侧地块',
          description: '两户村民因土地边界划分问题产生争执，需要调解',
          urgency: '中'
        }
      }
    ]

    complaintTemplates.forEach((template, index) => {
      const user = users[index % users.length]
      const status = statuses[Math.floor(Math.random() * statuses.length)]
      const createTime = new Date()
      createTime.setDate(createTime.getDate() - Math.floor(Math.random() * 30))
      
      cases.push({
        id: `complaint_${Date.now()}_${index}`,
        title: template.title,
        description: template.description,
        type: template.type,
        category: template.category,
        status: status,
        user: {
          id: `user_${index}`,
          name: user.name,
          phone: user.phone,
          avatar: ''
        },
        formData: template.formData,
        createTime: createTime.toISOString(),
        updateTime: new Date().toISOString(),
        assignee: status === 'pending' ? null : '管理员',
        deadline: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
        attachments: Math.floor(Math.random() * 3),
        comments: Math.floor(Math.random() * 5)
      })
    })
    
    return cases
  },

  // 加载统计数据
  loadStats() {
    // 基于实际案件数据计算统计
    const allCases = this.data.casesList
    const stats = {
      total: allCases.length,
      pending: allCases.filter(c => c.status === 'pending').length,
      approved: allCases.filter(c => c.status === 'approved').length,
      rejected: allCases.filter(c => c.status === 'rejected').length
    }
    
    this.setData({ stats })
  },

  // 从API数据更新统计数据
  updateStatsFromAPI(applications) {
    const stats = {
      total: applications.length,
      pending: applications.filter(app => app.status === 'pending').length,
      approved: applications.filter(app => app.status === 'approved').length,
      rejected: applications.filter(app => app.status === 'rejected').length
    }
    
    this.setData({ stats })
  },

  // 将申请数据转换为案件格式
  formatApplicationsToCases(applications) {
    return applications.map(app => ({
      id: app.id,
      title: '最低生活保障申请',
      description: '困难群众最低生活保障资格申请与复核',
      type: 'application',
      category: 'civil-affairs',
      subCategory: 'min-income',
      status: app.status,
      user: {
        id: app.userId,
        name: app.applicantName,
        phone: app.applicantPhone,
        avatar: ''
      },
      formData: {
        name: app.applicantName,
        idCard: app.applicantIdCard,
        applicationNo: app.applicationNo,
        phone: app.applicantPhone,
        address: app.applicantAddress,
        familySize: app.familySize.toString(),
        monthlyIncome: app.monthlyIncome.toString(),
        incomeSource: app.incomeSource,
        reason: app.difficultyReason
      },
      createTime: app.applyTime,
      updateTime: app.updatedAt,
      assignee: app.reviewerName || null,
      deadline: app.deadline,
      attachments: this.countAttachments(app),
      comments: 0
    }))
  },

  // 去重数据，确保没有重复的案件
  deduplicateCases(cases) {
    const seen = new Set()
    return cases.filter(caseItem => {
      if (seen.has(caseItem.id)) {
        console.log('发现重复案件，已过滤:', caseItem.id)
        return false
      }
      seen.add(caseItem.id)
      return true
    })
  },

  // 计算附件数量
  countAttachments(app) {
    let count = 0
    if (app.idCardImage) count++
    if (app.householdImage) count++
    if (app.incomeProofImage) count++
    return count
  },

  // 获取日期范围
  getDateRange(dateFilter) {
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    
    switch (dateFilter) {
      case 'today':
        return {
          start: today.toISOString().slice(0, 10),
          end: today.toISOString().slice(0, 10)
        }
      case 'week':
        const weekStart = new Date(today)
        weekStart.setDate(today.getDate() - today.getDay())
        return {
          start: weekStart.toISOString().slice(0, 10),
          end: today.toISOString().slice(0, 10)
        }
      case 'month':
        const monthStart = new Date(today.getFullYear(), today.getMonth(), 1)
        return {
          start: monthStart.toISOString().slice(0, 10),
          end: today.toISOString().slice(0, 10)
        }
      default:
        return { start: '', end: '' }
    }
  },

  // 搜索案件
  onSearchInput(e) {
    this.setData({ searchKeyword: e.detail.value })
  },

  onSearchConfirm() {
    this.loadCasesList(true)
  },

  onSearchClear() {
    this.setData({ searchKeyword: '' })
    this.loadCasesList(true)
  },

  // 筛选操作
  onStatusFilter(e) {
    const status = e.currentTarget.dataset.status
    this.setData({ statusFilter: status })
    this.loadCasesList(true)
  },


  onCategoryFilter(e) {
    const category = e.currentTarget.dataset.category
    this.setData({ categoryFilter: category })
    this.loadCasesList(true)
  },


  onDateFilter(e) {
    const date = e.currentTarget.dataset.date
    this.setData({ dateFilter: date })
    this.loadCasesList(true)
  },

  // 切换筛选面板
  toggleFilter() {
    this.setData({ showFilter: !this.data.showFilter })
  },

  // 重置筛选
  resetFilter() {
    this.setData({
      statusFilter: 'all',
      categoryFilter: 'all',
      dateFilter: 'all',
      searchKeyword: ''
    })
    this.loadCasesList(true)
  },

  // 案件操作
  onCaseTap(e) {
    const caseId = e.currentTarget.dataset.id
    console.log('点击查看详情按钮，案件ID:', caseId)
    
    if (!caseId) {
      wx.showToast({
        title: '案件ID不存在',
        icon: 'none'
      })
      return
    }
    
    console.log('准备跳转到案件详情页面...')
    wx.navigateTo({
      url: `/pages/admin/cases/detail/index?id=${caseId}`,
      success: () => {
        console.log('跳转成功')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({ 
          title: '页面跳转失败', 
          icon: 'none',
          duration: 3000
        })
      }
    })
  },

  // 快速操作
  onQuickAction(e) {
    const { action, id } = e.currentTarget.dataset
    const caseItem = this.data.casesList.find(item => item.id === id)
    
    if (!caseItem) return

    switch(action) {
      case 'approve':
        this.approveCase(id)
        break
      case 'reject':
        this.rejectCase(id)
        break
      case 'assign':
        this.assignCase(id)
        break
      case 'complete':
        this.completeCase(id)
        break
    }
  },

  // 批准案件
  approveCase(caseId) {
    wx.showModal({
      title: '确认操作',
      content: '确定要批准这个案件吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateCaseStatus(caseId, 'approved')
        }
      }
    })
  },

  // 拒绝案件
  rejectCase(caseId) {
    wx.showModal({
      title: '确认操作',
      content: '确定要拒绝这个案件吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateCaseStatus(caseId, 'rejected')
        }
      }
    })
  },

  // 分配案件
  assignCase(caseId) {
    wx.showActionSheet({
      itemList: ['分配给管理员A', '分配给管理员B', '分配给管理员C'],
      success: (res) => {
        this.updateCaseStatus(caseId, 'completed')
        wx.showToast({ title: '分配成功', icon: 'success' })
      }
    })
  },

  // 完成案件
  completeCase(caseId) {
    wx.showModal({
      title: '确认操作',
      content: '确定要完成这个案件吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateCaseStatus(caseId, 'approved')
        }
      }
    })
  },

  // 更新案件状态
  updateCaseStatus(caseId, status) {
    const casesList = this.data.casesList.map(item => {
      if (item.id === caseId) {
        return { ...item, status, updateTime: new Date().toISOString() }
      }
      return item
    })
    
    this.setData({ casesList })
    this.loadStats()
    
    wx.showToast({ 
      title: '操作成功', 
      icon: 'success' 
    })
  },

  // 批量操作
  onCaseSelect(e) {
    const caseId = e.currentTarget.dataset.id
    const selectedCases = [...this.data.selectedCases]
    
    const index = selectedCases.indexOf(caseId)
    if (index > -1) {
      selectedCases.splice(index, 1)
    } else {
      selectedCases.push(caseId)
    }
    
    this.setData({ 
      selectedCases,
      showBatchActions: selectedCases.length > 0
    })
  },

  onBatchApprove() {
    if (this.data.selectedCases.length === 0) return
    
    wx.showModal({
      title: '批量操作',
      content: `确定要批准选中的 ${this.data.selectedCases.length} 个案件吗？`,
      success: (res) => {
        if (res.confirm) {
          this.data.selectedCases.forEach(caseId => {
            this.updateCaseStatus(caseId, 'approved')
          })
          this.setData({ selectedCases: [], showBatchActions: false })
        }
      }
    })
  },

  onBatchReject() {
    if (this.data.selectedCases.length === 0) return
    
    wx.showModal({
      title: '批量操作',
      content: `确定要拒绝选中的 ${this.data.selectedCases.length} 个案件吗？`,
      success: (res) => {
        if (res.confirm) {
          this.data.selectedCases.forEach(caseId => {
            this.updateCaseStatus(caseId, 'rejected')
          })
          this.setData({ selectedCases: [], showBatchActions: false })
        }
      }
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadCasesList(true)
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      const nextPage = this.data.currentPage + 1
      this.setData({ currentPage: nextPage })
      this.performDataLoad(nextPage)
    }
  },


  // 格式化时间
  formatTime(timeStr) {
    const time = new Date(timeStr)
    const now = new Date()
    const diff = now - time
    
    if (diff < 60 * 1000) {
      return '刚刚'
    } else if (diff < 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 1000))}分钟前`
    } else if (diff < 24 * 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
    } else {
      return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
    }
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colors = {
      pending: '#dc2626',
      approved: '#059669',
      rejected: '#dc2626'
    }
    return colors[status] || '#64748b'
  },

})
